/**
 * 
 */
package com.kishimemo.gps;

import	java.util.List;

import android.app.Activity;
import android.location.LocationProvider;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;


/**
 * @author kishimoto kazuya
 *
 */
public class DataShowActivity extends Activity implements LocationListener,SensorEventListener {
    private LocationManager mLocationManager;
    private SensorManager mSensorManager;
    private boolean mIsMagSensor;
    private boolean mIsAccSensor;
    private static final int MATRIX_SIZE = 16;
    /* 回転行列 */
    float[]  inR = new float[MATRIX_SIZE];
    float[] outR = new float[MATRIX_SIZE];
    float[]    I = new float[MATRIX_SIZE];
 
    /* センサーの値 */
    float[] orientationValues   = new float[3];
    float[] magneticValues      = new float[3];
    float[] accelerometerValues = new float[3];
    
    
    /* 表示画面の要素 */
    TextView txtLatitude;
    TextView txtLongitude;
    TextView txtAccuracy;
    TextView txtAltitude;
    TextView txtTime;
    TextView txtSpeed;
    TextView txtBearing;
    TextView txtZaxis;
    TextView txtYaxis;
    TextView txtXaxis;
    TextView txtPercent;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.datashowactivity);
        txtLatitude = (TextView)findViewById(R.id.txtLatitude);
        txtLongitude = (TextView)findViewById(R.id.txtLongitude);
        txtAccuracy = (TextView)findViewById(R.id.txtAccuracy);
        txtAltitude = (TextView)findViewById(R.id.txtAltitude);
        txtTime = (TextView)findViewById(R.id.txtTime);
        txtSpeed = (TextView)findViewById(R.id.txtSpeed);
        txtBearing = (TextView)findViewById(R.id.txtBearing);
        txtZaxis = (TextView)findViewById(R.id.txtZaxis);
        txtYaxis = (TextView)findViewById(R.id.txtYaxis);
        txtXaxis = (TextView)findViewById(R.id.txtXaxis);
        txtPercent = (TextView)findViewById(R.id.txtPercent);
        
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);        
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if (mLocationManager != null) {
            mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
//                LocationManager.NETWORK_PROVIDER,
                0,
                0,
                this);
        }
        List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
        
        // センサマネージャへリスナーを登録(implements SensorEventListenerにより、thisで登録する)
        for (Sensor sensor : sensors) {
 
            if( sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
                mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
                mIsMagSensor = true;
            }
 
            if( sensor.getType() == Sensor.TYPE_ACCELEROMETER){
                mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
                mIsAccSensor = true;
            }
        }
    }
    
    @Override
    protected void onPause() {
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(this);
        }
        //センサーマネージャのリスナ登録破棄
        if (mIsMagSensor || mIsAccSensor) {
            mSensorManager.unregisterListener(this);
            mIsMagSensor = false;
            mIsAccSensor = false;
        }
        super.onPause();
    }

	
	/* (non-Javadoc)
	 * @see android.location.LocationListener#onLocationChanged(android.location.Location)
	 */
	public void onLocationChanged(Location location) {
        Log.v("----------", "----------");
        txtLatitude.setText(String.valueOf(location.getLatitude()));
        txtLongitude.setText(String.valueOf(location.getLongitude()));
        txtAccuracy.setText(String.valueOf(location.getAccuracy()));
        txtAltitude.setText(String.valueOf(location.getAltitude()));
        txtTime.setText(String.valueOf(location.getTime()));
        txtSpeed.setText(String.valueOf(location.getSpeed()));
        txtBearing.setText(String.valueOf(location.getBearing()));
        


	}

	/* (non-Javadoc)
	 * @see android.location.LocationListener#onProviderDisabled(java.lang.String)
	 */
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see android.location.LocationListener#onProviderEnabled(java.lang.String)
	 */
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle)
	 */
	public void onStatusChanged(String provider, int status, Bundle extras) {
        switch (status) {
        case LocationProvider.AVAILABLE:
            Log.v("Status", "AVAILABLE");
            break;
        case LocationProvider.OUT_OF_SERVICE:
            Log.v("Status", "OUT_OF_SERVICE");
            break;
        case LocationProvider.TEMPORARILY_UNAVAILABLE:
            Log.v("Status", "TEMPORARILY_UNAVAILABLE");
            break;
        }
	}
    public void onSensorChanged(SensorEvent event) { 

//    	if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE){
//    		return;
//    	}
//     
    	switch (event.sensor.getType()) {
    		case Sensor.TYPE_MAGNETIC_FIELD:
    			magneticValues = event.values.clone();
    			break;
    		case Sensor.TYPE_ACCELEROMETER:
    			accelerometerValues = event.values.clone();
    			break;

    	}
  
    	if (magneticValues != null && accelerometerValues != null) {
  
    		SensorManager.getRotationMatrix(inR, I, accelerometerValues, magneticValues);
  
    		//Activityの表示が縦固定の場合。横向きになる場合、修正が必要です
    		SensorManager.remapCoordinateSystem(inR, SensorManager.AXIS_X, SensorManager.AXIS_Z, outR);
    		SensorManager.getOrientation(outR, orientationValues);
  
     		txtXaxis.setText(String.valueOf( radianToDegree(orientationValues[0]) ));
    		txtYaxis.setText(String.valueOf( radianToDegree(orientationValues[2]) ));
    		txtZaxis.setText(String.valueOf( 90-radianToDegree(orientationValues[1]) ));
    		txtPercent.setText(String.valueOf(java.text.NumberFormat.getPercentInstance().format(Math.tan(Math.PI/2-orientationValues[1]))));
    	}
    }
    	
    int radianToDegree(float rad) {
    	return (int) Math.floor(Math.toDegrees(rad));
    }

	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
          

}
